from lib.net.index import wlan
from lib.mqtt.index import client
from lib.clock import ticker_clock
from lib.config.index import mqtt_config,sensor_config
import asyncio
import json

__service__ = "mqtt_client"
__description__ = "mqtt client sub and pub"


keep_alive = max(mqtt_config.get_keepalive() / 2, 10)  # 最小10S ping
timer = ticker_clock.TickerClock(keep_alive * 1000)
is_debug = mqtt_config.is_debug()


def play_msg_audio(msg):
    from lib.sensors.max98357 import Max98357
    max98357_config = sensor_config.get_sensor("MAX98357")
    sck = max98357_config["sck"]
    ws = max98357_config["ws"]
    sd = max98357_config["sd"]
    max98357 = Max98357(sck, ws, sd)
    max98357.network_play(msg)


def msg_handler(msg_content):
    # play_msg_audio(msg_content)
    pass


def callback(topic, msg):
    print("接收到订阅消息: ", topic, msg)
    data = msg.decode("utf-8")
    json_data = json.loads(data)
    msg_content = ""
    if "msg" in json_data:
        msg_content = json_data["msg"]
        msg_handler(msg_content)


def keepalive_timer():
    if is_debug:
        print("mqtt ping diff: ", timer.get_diff())
    if timer.check():
        if is_debug:
            print("mqtt publish ping")
        client.ping()


def init():
    wlan.connect()
    client.set_callback(callback)
    client.connect()
    client.subscribe()


async def run():
    while True:
        keepalive_timer()
        await client.wait_msg()
        await asyncio.sleep(1)
